package com.pig4cloud.pigx.wxApi.util;


import com.pig4cloud.pigx.wxApi.config.ApplicationContextHolder;
import com.pig4cloud.pigx.wxApi.config.JwtAuthenticatioToken;
import com.pig4cloud.pigx.wxApi.config.UserStatusEnum;
import com.pig4cloud.pigx.wxApi.entity.SysUserInfo;
import com.pig4cloud.pigx.wxApi.service.UserInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;

import javax.servlet.http.HttpServletRequest;

/**
 * @program: lawyer
 * @description: security
 * @author: Mr.An
 * @create: 2020-12-03 15:50
 **/
@Slf4j
public class SecurityUtils {

	private static UserInfoService userInfoService = ApplicationContextHolder.getContext().getBean(UserInfoService.class);

	/**
	 * 系统登录认证
	 * @param request
	 * @param username
	 * @param password
	 * @param authenticationManager
	 * @return
	 */
	public static JwtAuthenticatioToken login(HttpServletRequest request, String username, String password, AuthenticationManager authenticationManager) {

		JwtAuthenticatioToken token = new JwtAuthenticatioToken(username, password);
		token.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
		// 执行登录认证过程
	    Authentication authentication = authenticationManager.authenticate(token);
	    // 认证成功存储认证信息到上下文
	    SecurityContextHolder.getContext().setAuthentication(authentication);
		// 生成令牌并返回给客户端
	    token.setToken(JwtTokenUtils.generateToken(authentication));
		//向redis里面存入数据，以用户号为主键

		return token;
	}

	/**
	 * 获取令牌进行认证
	 * @param request
	 */
	public static void checkAuthentication(HttpServletRequest request) {
		// 获取令牌并根据令牌获取登录认证信息
		Authentication authentication = JwtTokenUtils.getAuthenticationeFromToken(request);
		if (authentication!=null){
			String username=null;
			Object principal=authentication.getPrincipal();
			if (principal instanceof UserDetails){
				UserDetails login = (UserDetails)authentication.getPrincipal();
				username=login.getUsername();
			}else if (principal instanceof String){
				username=principal.toString();
			}
			log.info("=================checkAuthentication=================username={}",username);
			if ("anonymousUser".equals(username)){
				authentication=null;
			}
			boolean isPhone = VerifyUtil.isPhone(username);
			boolean isEmail = VerifyUtil.isEmail(username);
			SysUserInfo userInfo=null;
			//2.校验用户是否存在
			if (isPhone == true) {
				userInfo = userInfoService.getUserByPhone(username);
			} else if (isEmail == true){
				userInfo = userInfoService.getUserByEmail(username);
			}

			if(userInfo==null||userInfo.getStatus()== UserStatusEnum.DISABLE.getCode()){
				authentication=null;
			}else{
				//从用户表里面验证token数据
				String token = JwtTokenUtils.getToken(request);
				String personalWeb = userInfo.getPersonalWeb();
				if(!token.equals(personalWeb))
				{
					log.info("---------------------------"+token);
					authentication=null;
				}
			}
		}
		// 设置登录认证信息到上下文
		SecurityContextHolder.getContext().setAuthentication(authentication);
	}

	
	  public static String getLoginUserName() {
	        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
	        if (authentication==null){
	        	return null;
			}
		  Object principal=authentication.getPrincipal();
		  if (principal instanceof UserDetails){
			  UserDetails login = (UserDetails)authentication.getPrincipal();
			  return login.getUsername();
		  }else if (principal instanceof String){
			  return principal.toString();
		  }else{
		  	return null;
		  }
	    }
	/**
	 * 获取用户名
	 * @return
	 */
	public static String getUsername(Authentication authentication) {
		String username = null;
		if(authentication != null) {
			Object principal = authentication.getPrincipal();
			if(principal != null && principal instanceof UserDetails) {
				username = ((UserDetails) principal).getUsername();
			}
		}
		return username;
	}
	
	/**
	 * 获取当前登录信息
	 * @return
	 */
	public static Authentication getAuthentication() {
		if(SecurityContextHolder.getContext() == null) {
			return null;
		}
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		return authentication;
	}
	
}
